package com.huaxin.hxcloud.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.HeadPortrait;
import com.huaxin.common.Entity.UserDTO;
import com.huaxin.common.Global;
import com.huaxin.common.media.SelectImageActivity;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ModifyUserInfoActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2017/3/3.
 */

public class UserInfoFragment extends BaseFragment implements SelectImageActivity.Callback {
    @BindView(R.id.more)
    TextView        more;
    @BindView(R.id.toolbar)
    Toolbar         toolbar;
    @BindView(R.id.tv_nick_name)
    TextView        tvNickName;
    @BindView(R.id.tv_sex)
    TextView        tvSex;
    @BindView(R.id.tv_phone)
    TextView        tvPhone;
    @BindView(R.id.tv_e_mail)
    TextView        tvEMail;
    @BindView(R.id.tv_company)
    TextView        tvCompany;
    @BindView(R.id.tv_title)
    TextView        tvTitle;
    @BindView(R.id.tv_intro)
    TextView        mTvIntro;
    @BindView(R.id.ll_org_info)
    LinearLayout    llOrgInfo;
    @BindView(R.id.ll_nick_name)
    LinearLayout    llNickName;
    @BindView(R.id.ll_sex)
    LinearLayout    llSex;
    @BindView(R.id.iv_head_portrait)
    AvatarImageView ivHeadPortrait;
    @BindView(R.id.ll_head_portrait)
    LinearLayout    llHeadPortrait;
    UserDTO _user;
    private static final String TAG = "UserInfoFragment";

    @Override
    protected int getContentViewId() {
        return R.layout.activity_user_info;
    }

    private List<LocalMedia> selectList = new ArrayList<>();

    protected void updateView() {
        _user = Global.user;
        if (_user != null) {
            loadText(mTvIntro, _user.getUserIntroduction());
            loadText(tvNickName, _user.getNickName());
            loadText(tvSex, _user.getSex().equals("0") ? "男" : "女");
            HxAvatarImageGlide.getInstance().setHeadImage(getContext(), _user.getImgUrl(), _user.getNickName(), ivHeadPortrait);
            // loadImg(ivHeadPortrait, _user.getImgUrl(), R.drawable.head_portrait);
        }

        if (Global.user.getOrgCode() == null) {
            llOrgInfo.setVisibility(View.GONE);
        } else {
            loadText(tvPhone, _user.getTelPhone(), "暂无");
            loadText(tvEMail, _user.getEmail(), "暂无");
            loadText(tvCompany, _user.getCompany(), "暂无");
            loadText(tvTitle, _user.getTitle(), "暂无");
        }
    }

    @Override
    protected void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
        toolbar.setTitle("我的资料");
        updateView();
    }


    @OnClick({R.id.ll_nick_name, R.id.ll_sex, R.id.ll_head_portrait, R.id.rl_gen_code, R.id.ll_intro})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_nick_name:
                ((ModifyUserInfoActivity) getActivity()).startModifyNameFragment();
                break;
            case R.id.ll_sex:
                ((ModifyUserInfoActivity) getActivity()).startModifySexFragment();
                break;
            case R.id.ll_head_portrait:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)//单选
                        .enableCrop(false)// 是否裁剪
                        .compress(true)// 是否压缩
                        .selectionMedia(selectList)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                //SelectImageActivity.selectImage(getContext(), true, true, this);
                break;
            case R.id.rl_gen_code:
                ((ModifyUserInfoActivity) getActivity()).startGenCodeFragment();
                break;
            case R.id.ll_intro://简介
                ((ModifyUserInfoActivity) getActivity()).startIntroFragment();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // adapter.setList(selectList);
                    // adapter.notifyDataSetChanged();
                    //DebugUtil.i(TAG, "onActivityResult:" + selectList.size());
                    Log.d(TAG, selectList.size() + "--->path-->" + selectList.get(0).getPath());
                    ApiCommitHead(selectList.get(0).getPath());
                    break;
            }
        }
    }


    @Override
    public void doSelectDone(String[] images, String[] compress) {
        if (images != null && compress.length == 1) {
            ApiCommitHead(compress[0]);
            //            ClipImageActivity.start(getActivity(),images[0], this);
        }
    }

    private void ApiCommitHead(final String path) {
        final Dialog dialog = DialogUtil.getWaitDialog(getContext(), "上传中...");
        dialog.show();
        Call<HeadPortrait> call = getRequestApi().commitHead(RequestHelper.createFilePart(new File(path)));
        autoClose(call);
        call.enqueue(new Callback<HeadPortrait>() {
            @Override
            public void onResponse(Call<HeadPortrait> call, Response<HeadPortrait> response) {
                dialog.dismiss();
                if (response.isSuccessful() && response.body() != null) {
                    HeadPortrait headPortrait = response.body();
                    if (headPortrait.isSuccessful()) {
                        ToastUtil.showToast(headPortrait.getMsg());
                        loadImg(ivHeadPortrait, headPortrait.getImg());
//                        ChatHelper.sendUpdateUserIcon(headPortrait.getImg());
                        //                        Glide.with(getContext()).load(path).skipMemoryCache(true).into(ivHeadPortrait);
                        Global.user.setImgUrl(headPortrait.getImg());
                        Log.d(TAG, "----->" + headPortrait.getImg());
                        String clientId = "" + Global.user.getUserId();
//                        ContactHelper.getContact(clientId).setIcon(headPortrait.getImg());
                    } else {
                        ToastUtil.showToast(headPortrait.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<HeadPortrait> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }


}
